package com.example.lenovo.appstore.utils;

import android.animation.ValueAnimator;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.util.Log;

import com.example.lenovo.appstore.R;
import com.example.lenovo.appstore.activity.AppInfoActivity;
import com.jiang.android.pbutton.CProgressButton;

import org.xutils.common.Callback;
import org.xutils.common.task.PriorityExecutor;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.File;

import androidx.appcompat.app.AlertDialog;
import androidx.core.content.FileProvider;

/**
 * 项目名称：AppStore
 *  下载APK工具
 * @Author 郭迎辉
 * Create by 9:25 on 2019/3/22.
 * Describe:
 */
public class DownLoadAPKUtil {
    private  Context context;
    public static boolean isFinish=false;

    public static   void  downLoadAPK(final ValueAnimator valueAnimator, String appname, String url, final CProgressButton install, Callback.Cancelable cancelable){

//        执行网络请求操作

//        downLoad.setText("下载中...");
        RequestParams params = new RequestParams(url);
        params.setAutoRename(false);  //设置是否根据头信息命名文件
        params.setAutoResume(true);  //设置文件下载断点续传
        params.setExecutor(new PriorityExecutor(2,true));  //设置加载图片的线程池
        params.setCancelFast(true);  //设置是否可以立即停止
//        设置缓存的路径
        String filePath=AppContext.getInstance().getExternalFilesDir(null)+"/download/"+appname+".apk";

//        if(new File(filePath).exists()){
//            //已存在  询问是否删除
//            AlertDialog.Builder builder = new AlertDialog.Builder(ProductInfoActivity.this);
//            builder.setTitle(getResources().getString(R.string.tishi)).setMessage(getResources().getString(R.string.quedinganzhuang))
//                    .setPositiveButton(getResources().getString(R.string.yes), new DialogInterface.OnClickListener() {
//                        @Override
//                        public void onClick(DialogInterface dialog, int which) {
////                              执行apk安装的步骤
//                            deleteSingleFile(filePath);
//
////                                deleteSingleFile(file.toString());
////                                Log.e("删除安装包==","删除成功");
//
//                        }
//                    }).setNegativeButton(getResources().getString(R.string.fail), new DialogInterface.OnClickListener() {
//            });
//            builder.create().show();
//
//        }else{
//
//        }
        params.setSaveFilePath(filePath);
        cancelable =  x.http().get(params, new Callback.ProgressCallback<File>() {
            @Override
            public void onSuccess(final File file) {
//                请求成功时，回调的方法
                AlertDialog.Builder builder = new AlertDialog.Builder(AppContext.getInstance());
                builder.setTitle(AppContext.getInstance().getResources().getString(R.string.tishi)).setMessage(AppContext.getInstance().getResources().getString(R.string.quedinganzhuang))
                        .setPositiveButton(AppContext.getInstance().getResources().getString(R.string.yes), new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
//                              执行apk安装的步骤
//                                downLoad.setImageResource(R.mipmap.download_apk_);
//                                downLoad.setClickable(true);
                                Intent intent = new Intent(Intent.ACTION_VIEW);
                                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                if(Build.VERSION.SDK_INT >= 24){//大于7.0
                                    Uri apkUri=FileProvider.getUriForFile(AppContext.getInstance(),"com.example.lenovo.appstore.fileprovider",file);
                                    //添加这一句表示对目标应用临时授权该Uri所代表的文件
                                    intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                                    intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
                                }else {
                                    intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");

                                }
                                AppContext.getInstance().startActivity(intent);

//                                deleteSingleFile(file.toString());
//                                Log.e("删除安装包==","删除成功");

                            }
                        }).setNegativeButton(AppContext.getInstance().getResources().getString(R.string.fail), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
//                        deleteSingleFile(file.toString());
                    }
                });
                builder.create().show();
            }
            @Override
            public void onError(Throwable throwable, boolean b) {
                Log.e("onError",throwable.getMessage().toString());
//              请求失败时，会执行的方法
            }
            @Override
            public void onCancelled(CancelledException e) {
                Log.e("onCancelled",e.getMessage().toString());
//              请求被取消时，会执行的方法
//                progressDialog.dismiss();
                install.normal(1);
                valueAnimator.pause();

//                downLoad.setImageResource(R.mipmap.download_apk_);
//                downLoad.setClickable(true);
            }
            @Override
            public void onFinished() {
//              请求完成时，会执行的方法
                Log.e("onFinished","onFinished");
                if(isFinish){
                    install.normal(0);
                }else{
                    install.normal(1);
                }
//                install.normal(2);
//                install.setText("下载");
//                install.
            }
            @Override
            public void onWaiting() {
                Log.e("onWaiting","onWaiting");
//                downLoad.setImageResource(R.mipmap.download_apk_);
//                downLoad.setClickable(true);
            }
            @Override
            public void onStarted() {
                Log.e("onStarted","onStarted");
//                开始网络请求时，会执行的方法
                install.startDownLoad();
                valueAnimator.start();
//                CProgess(0);
            }
            @Override
            public void onLoading(long total, long current, boolean b) {
                Log.e("total","onLoading=="+total);
                Log.e("current","onLoading"+current);
                Log.e("b","onLoading"+b);
                if(total==current){
                    isFinish=true;
                }else{
                    isFinish=false;
                }

//                  设置对话框当中的进度条
//                progressDialog.setProgress((int)(current*100/total));
                install.download((int)(current*100/total));

            }
        });



    }
}
